<template>
  <div class="knowledge-base">
    <!-- 左侧资料库列表 -->
    <KnowledgeBaseGroupList
      :groups="store.knowledgeBaseGroups"
      :selected-group="store.selectedGroup"
      :is-loading="store.isLoading"
      @select-group="handleSelectGroup"
      @delete-group="handleDeleteGroup"
      @create-group="showCreateGroupModal = true"
    />
    
    <!-- 中间树状文件夹结构 -->
    <div class="folder-tree">
      <div class="tree-header">
        <h3>资料库目录</h3>
        <div class="header-buttons">
          <button 
            class="init-folder-btn" 
            @click="showInitModal = true"
            :disabled="store.isLoading"
            title="初始化资料库目录"
            v-if="isAdmin || isAdvancedLibraryAdmin || isEditRole || isAssignRole"
          >
            <span>↻</span>
          </button>
          <button 
            class="add-folder-btn" 
            @click="createRootFolder"
            :disabled="store.isLoading"
            title="新建资料库目录"
            v-if="isAdmin || isAdvancedLibraryAdmin || isEditRole || isAssignRole"
          >
            <span>+</span>
          </button>
        </div>
      </div>
      <div class="tree-content">
        <template v-for="folder in store.knowledgeBases" :key="folder.id">
          <FolderTreeItem 
            :folder="folder" 
            @select="selectFolder"
            @toggle="toggleFolder"
            @delete-folder="deleteKnowledgeBase"
          />
        </template>
      </div>
    </div>

    <!-- 右侧文件列表 -->
    <div class="file-list">
      <div class="file-list-header">
        <div class="header-content">
          <h3>{{ store.selectedFolder?.name || '请选择文件夹' }}</h3>
          <div class="header-buttons">
            <button 
              v-if="store.selectedFolder && (isAdmin || isAdvancedLibraryAdmin || isEditRole || isAssignRole)"
              class="upload-btn" 
              @click="showUploadModal = true"
            >
              <span>+</span> 上传文件
            </button>
            <button 
              class="transfer-btn"
              @click="toggleTransferList"
              :class="{ 'has-active': transferStore.activeTasksCount > 0 }"
              v-if="isAdmin || isAdvancedLibraryAdmin || isEditRole || isAssignRole"
            >
              <i class="fa fa-upload"></i>
              <span v-if="transferStore.activeTasksCount > 0" class="transfer-count">
                {{ transferStore.activeTasksCount }}
              </span>
            </button>
          </div>
        </div>
      </div>
      <div 
        class="file-list-content"
        v-if="store.selectedFolder"
        @scroll="handleScroll"
      >
        <table>
          <thead>
            <tr>
              <th>文件名</th>
              <th>大小</th>
              <th>创建时间</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="file in store.selectedFolder.files" :key="file.id">
              <td>
                <div class="file-name" @click="handlePreview(file)" :class="{ 'clickable': true }">
                  <img :src="getFileIcon(file.type)" :alt="file.type" class="file-icon">
                  {{ file.name }}
                </div>
              </td>
              <td>{{ file.size }}</td>
              <td>{{ formatDate(file.createTime) }}</td>
              <td>
                <div class="action-buttons">
                  <!-- <button class="preview-btn" @click="handlePreview(file)" title="预览">预览</button> -->
                  <button 
                    class="delete-btn" 
                    @click="handleDelete(file)" 
                    title="删除"
                    v-if="isAdmin || isAdvancedLibraryAdmin || isAssignRole"
                  >
                    删除
                  </button>
                </div>
              </td>
            </tr>
          </tbody>
        </table>
        <div v-if="store.loadingMore" class="loading-more">
          加载中...
        </div>
        <div v-if="!store.hasMoreFiles && store.selectedFolder.files.length > 0" class="no-more">
          没有更多文件了
        </div>
        <div v-if="!store.isLoading && store.selectedFolder?.files.length === 0" class="empty-folder">
          <template v-if="store.selectedFolder?.children?.length > 0">
            该文件夹没有文件，包含 {{ store.selectedFolder.children.length }} 个子文件夹
          </template>
          <template v-else>
            该文件夹为空
          </template>
        </div>
      </div>
      <div v-else class="empty-state">
        请选择左侧文件夹查看文件
      </div>
    </div>
  </div>

  <!-- 上传文件模态框 -->
  <UploadFileModal
    v-if="showUploadModal"
    :show="showUploadModal"
    @close="showUploadModal = false"
    @upload="handleFileUpload"
  />

  <!-- 创建文件夹模态框 -->
  <CreateFolderModal
    v-if="showCreateFolderModal"
    :show="showCreateFolderModal"
    @close="showCreateFolderModal = false"
    @create="handleCreateFolder"
  />
  
  <!-- 传输列表组件 -->
  <Teleport to="body">
    <TransferListModal />
  </Teleport>
  
  <!-- 初始化知识库模态框 -->
  <InitKnowledgeBaseModal
    v-if="showInitModal"
    :show="showInitModal"
    @close="showInitModal = false"
    @init="handleInitKnowledgeBase"
  />
  
  <!-- 创建资料库模态框 -->
  <CreateGroupModal
    v-if="showCreateGroupModal"
    :show="showCreateGroupModal"
    @close="showCreateGroupModal = false"
    @create="handleCreateGroup"
  />
</template>

<style scoped>
.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
}

.upload-btn {
  background-color: #4CAF50;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 5px;
  font-size: 14px;
}

.upload-btn:hover {
  background-color: #45a049;
}

.upload-btn span {
  font-size: 18px;
  font-weight: bold;
}

.add-folder-btn {
  background-color: #4CAF50;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 5px;
  font-size: 14px;
  transition: background-color 0.2s;
}

.add-folder-btn:hover:not(:disabled) {
  background-color: #45a049;
}

.add-folder-btn:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}

.add-folder-btn span {
  font-size: 18px;
  font-weight: bold;
}
</style>

<script setup lang="ts">
import { onMounted, ref,computed } from 'vue';
import { useKnowledgeBaseStore } from '../stores/knowledgebaseStore';
import { useTransferStore } from '../stores/transferStore';
import type { KnowledgeFile, KnowledgeBaseGroup } from '../stores/knowledgebaseStore';
import FolderTreeItem from '../components/knowledge/FolderTreeItem.vue';
import UploadFileModal from '../components/knowledge/UploadFileModal.vue';
import CreateFolderModal from '../components/knowledge/CreateFolderModal.vue';
import TransferListModal from '../components/knowledge/TransferListModal.vue';
import InitKnowledgeBaseModal from '../components/knowledge/InitKnowledgeBaseModal.vue';
import KnowledgeBaseGroupList from '../components/knowledge/KnowledgeBaseGroupList.vue';
import CreateGroupModal from '../components/knowledge/CreateGroupModal.vue';
import { ElMessage } from 'element-plus';
import { User } from '../types';

const store = useKnowledgeBaseStore();
const transferStore = useTransferStore();
const showUploadModal = ref(false);
const showCreateFolderModal = ref(false);
const showInitModal = ref(false);
const showCreateGroupModal = ref(false);

// 获取当前登录用户信息
const userInfoStr = localStorage.getItem('userInfo');
const currentUser = ref<User | null>(userInfoStr ? JSON.parse(userInfoStr) : null);
const isAdmin = computed(() => currentUser.value?.roleName === '超级管理员');
const isAdvancedLibraryAdmin = computed(() => {
  if (isAdmin.value) return false;
  if (!currentUser.value?.knowledgeBaseGroupRoleInfos) return false;
  return Object.entries(currentUser.value.knowledgeBaseGroupRoleInfos).some(
    ([groupId, roleId]) => groupId === store.selectedGroup?.id && roleId === 6
  );
});
const isEditRole = computed(() => {
  if (isAdmin.value || isAdvancedLibraryAdmin.value) return false;
  if (!currentUser.value?.knowledgeBaseGroupRoleInfos) return false;
  return Object.entries(currentUser.value.knowledgeBaseGroupRoleInfos).some(
    ([groupId, roleId]) => groupId === store.selectedGroup?.id && roleId === 7
  );
});
const isAssignRole = computed(() => {
  if (isAdmin.value || isAdvancedLibraryAdmin.value) return false;
  if (!currentUser.value?.knowledgeBaseGroupRoleInfos) return false;
  return Object.entries(currentUser.value.knowledgeBaseGroupRoleInfos).some(
    ([groupId, roleId]) => groupId === store.selectedGroup?.id && roleId === 11
  );
});

// 处理初始化知识库
const handleInitKnowledgeBase = async (path: string) => {
  if (!store.selectedGroup) {
    ElMessage.error('请先选择资料库');
    return;
  }
  await store.initKnowledgeBase(path, store.selectedGroup.id);
};

// 切换传输列表显示
const toggleTransferList = () => {
  transferStore.toggleShow();
};

// 处理选择资料库
const handleSelectGroup = async (group: KnowledgeBaseGroup) => {
  await store.selectGroup(group);
};

// 处理删除资料库
const handleDeleteGroup = async (groupId: string) => {
  const success = await store.deleteKnowledgeBaseGroup(groupId);
  if (success) {
    // 如果删除成功且还有其他资料库，自动选择第一个
    if (store.knowledgeBaseGroups.length > 0) {
      await store.selectGroup(store.knowledgeBaseGroups[0]);
    }
  }
};

// 处理创建资料库
const handleCreateGroup = async (name: string, permission: number) => {
  const success = await store.createKnowledgeBaseGroup(name, permission);
  if (success) {
    showCreateGroupModal.value = false;
    // 如果创建成功，自动选择新创建的资料库
    if (store.knowledgeBaseGroups.length > 0) {
      const newGroup = store.knowledgeBaseGroups.find(g => g.name === name);
      if (newGroup) {
        await store.selectGroup(newGroup);
      }
    }
  }
};

  // 处理文件上传
  const handleFileUpload = async (file: File) => {
    if (!store.selectedFolder) return;
    
    const success = await store.uploadFile(store.selectedFolder.id, file);
    if (success) {
      showUploadModal.value = false;
    }
  };

// 创建根节点知识库
const createRootFolder = async () => {
  if (!store.selectedGroup) {
    ElMessage.error('请先选择一个资料库');
    return;
  }
  
  const defaultName = `新建知识库目录`;
  const success = await store.createKnowledgeBase(defaultName, '1', store.selectedGroup.id); // '1' 表示根目录，传入选中的资料库ID
  if (success) {
    // 刷新知识库列表
    await store.fetchKnowledgeBases('1', true);
    
    // 如果有文件夹，自动选择第一个
    if (store.knowledgeBases.length > 0) {
      await store.selectFolder(store.knowledgeBases[0]);
    }
  }
};

// 处理创建文件夹
const handleCreateFolder = async (folderName: string) => {
  if (!store.selectedFolder || !store.selectedGroup) return;
  
  const success = await store.createKnowledgeBase(folderName, store.selectedFolder.id, store.selectedGroup.id);
  if (success) {
    // 刷新当前文件夹的子文件夹
    await store.fetchKnowledgeBases(store.selectedFolder.id, true);
  }
};
// 不要解构store中的状态，这会导致失去响应性
// 直接使用store.xxx来访问状态
const {
  fetchKnowledgeBases,
  deleteFile,
  deleteKnowledgeBase,
  toggleFolder,
  selectFolder,
  loadMoreFiles,
  previewFile
} = store;

// 初始化加载
onMounted(async () => {
  try {
    // 先加载资料库列表
    await store.fetchKnowledgeBaseGroups();
    
    // 如果有资料库，自动选择第一个
    if (store.knowledgeBaseGroups.length > 0) {
      await store.selectGroup(store.knowledgeBaseGroups[0]);
    }
    
    // 强制刷新，确保获取最新数据
    await fetchKnowledgeBases('1', true);
    
    // 添加延迟确保数据已更新
    await new Promise(resolve => setTimeout(resolve, 100));
    
    // 如果有文件夹，自动选择第一个
    if (store.knowledgeBases.length > 0) {
      const firstFolder = store.knowledgeBases[0];
      console.log('初始化选择第一个文件夹:', firstFolder.id, firstFolder.name);
      
      // 先加载子文件夹，确保children属性有值
      await toggleFolder(firstFolder);
      
      // 然后选择该文件夹
      await selectFolder(firstFolder);
      
      // 打印选中文件夹的children信息
      console.log('选中文件夹的children:', 
        store.selectedFolder?.children ? 
        `存在，长度为${store.selectedFolder.children.length}` : 
        '不存在');
    } else {
      // 如果没有文件夹，可能是加载失败，尝试再次加载
      console.log('未找到文件夹，尝试重新加载...');
      await new Promise(resolve => setTimeout(resolve, 1000));
      await fetchKnowledgeBases('1', true);
      
      // 再次检查并选择第一个文件夹
      if (store.knowledgeBases.length > 0) {
        const firstFolder = store.knowledgeBases[0];
        
        // 先加载子文件夹，确保children属性有值
        await toggleFolder(firstFolder);
        
        // 然后选择该文件夹
        await selectFolder(firstFolder);
      }
    }
  } catch (error) {
    console.error('初始化加载失败:', error);
  }
});

// 处理文件预览
const handlePreview = async (file: KnowledgeFile) => {
  await previewFile(file);
};

// 处理文件删除
const handleDelete = async (file: KnowledgeFile) => {
  if (confirm(`确定要删除文件 "${file.name}" 吗？`)) {
    await deleteFile(file.id);
  }
};

// 节流函数
const throttle = <T extends (...args: any[]) => any>(
  func: T,
  delay: number
): ((...args: Parameters<T>) => void) => {
  let lastCall = 0;
  return (...args: Parameters<T>) => {
    const now = Date.now();
    if (now - lastCall >= delay) {
      lastCall = now;
      func(...args);
    }
  };
};

// 处理滚动加载
const handleScroll = throttle((event: Event) => {
  const target = event.target as HTMLElement;
  const { scrollTop, scrollHeight, clientHeight } = target;
  
  // 当滚动到距离底部100px时触发加载更多
  if (scrollHeight - scrollTop - clientHeight < 100 && !store.loadingMore && store.hasMoreFiles) {
    loadMoreFiles();
  }
}, 200); // 200ms的节流时间

// 获取文件图标
const getFileIcon = (type: string) => {
  // 这里可以根据文件类型返回不同的图标URL
  const iconMap: Record<string, string> = {
    pdf: '/icons/pdf.svg',
    docx: '/icons/word.svg',
    xlsx: '/icons/excel.svg',
    pptx: '/icons/powerpoint.svg',
    default: '/icons/file.svg'
  };
  return iconMap[type] || iconMap.default;
};

// 格式化日期
const formatDate = (dateString: string) => {
  const date = new Date(dateString);
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  });
};
</script>

<style scoped>
.knowledge-base {
  display: flex;
  height: 100vh; /* 使用视口高度单位，确保占满整个屏幕高度 */
  gap: 20px;
  padding: 20px;
  background-color: #f5f5f5;
  overflow: hidden;
  box-sizing: border-box; /* 确保padding不会增加元素总高度 */
}

.folder-tree {
  flex: 0 0 250px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
}

.tree-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px;
  border-bottom: 1px solid #e0e0e0;
}

.tree-header h3 {
  margin: 0;
  color: #333;
}

.header-buttons {
  display: flex;
  gap: 8px;
}

.add-folder-btn {
  width: 28px;
  height: 28px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  padding: 0;
  transition: all 0.2s;
}

.add-folder-btn:hover:not(:disabled) {
  background-color: #45a049;
}

.add-folder-btn:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}

.add-folder-btn span {
  font-size: 18px;
  font-weight: bold;
}

.init-folder-btn {
  width: 28px;
  height: 28px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #2196F3;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  padding: 0;
  transition: background-color 0.2s;
}

.init-folder-btn:hover:not(:disabled) {
  background-color: #0b7dda;
}

.init-folder-btn:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}

.init-folder-btn span {
  font-size: 18px;
  font-weight: bold;
}

.tree-content {
  flex: 1;
  overflow-y: auto;
  padding: 12px;
  max-height: calc(100vh - 120px); /* 限制最大高度，减去头部和其他元素的高度 */
}

.file-list {
  flex: 1;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
}

.file-list-header {
  padding: 16px;
  border-bottom: 1px solid #e0e0e0;
}

.file-list-header h3 {
  margin: 0;
  color: #333;
}

.file-list-content {
  flex: 1;
  overflow-y: auto;
  padding: 12px;
}

table {
  width: 100%;
  border-collapse: collapse;
}

th, td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #e0e0e0;
}

th {
  font-weight: 600;
  color: #666;
  background-color: #f9f9f9;
}

.file-name {
  display: flex;
  align-items: center;
  gap: 8px;
}

.file-icon {
  width: 20px;
  height: 20px;
  object-fit: contain;
}

.delete-btn {
  padding: 4px 12px;
  border: none;
  border-radius: 4px;
  background-color: #ff4d4f;
  color: white;
  cursor: pointer;
  transition: background-color 0.2s;
}

.delete-btn:hover {
  background-color: #ff7875;
}

.preview-btn {
  padding: 4px 12px;
  border: none;
  border-radius: 4px;
  background-color: #1890ff;
  color: white;
  cursor: pointer;
  transition: background-color 0.2s;
}

.preview-btn:hover {
  background-color: #40a9ff;
}

.action-buttons {
  display: flex;
  gap: 8px;
}

.clickable {
  cursor: pointer;
}

.clickable:hover {
  text-decoration: underline;
  color: #1890ff;
}

.loading-more {
  text-align: center;
  padding: 16px;
  color: #666;
}

.no-more {
  text-align: center;
  padding: 16px;
  color: #999;
}

.empty-folder {
  text-align: center;
  padding: 32px;
  color: #999;
}

.empty-state {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #999;
  font-size: 16px;
}

/* 传输按钮样式 */
.header-buttons {
  display: flex;
  gap: 12px;
  align-items: center;
}

.transfer-btn {
  position: relative;
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background: #f0f0f0;
  border: none;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s;
}

.transfer-btn:hover {
  background: #e0e0e0;
}

.transfer-btn.has-active {
  color: #1890ff;
}

.transfer-count {
  position: absolute;
  top: -4px;
  right: -4px;
  background: #ff4d4f;
  color: white;
  border-radius: 50%;
  width: 16px;
  height: 16px;
  font-size: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>